using UnityEngine;

[AddComponentMenu("Scripts/ DragItem")]
public class DragItem : UIDragDropItem
{
	public GameObject prefab;
	public bool rotatePlacedObject;
	private float offset = 0.5F;  //Cube wall divided by two

	protected override void OnDragDropRelease (GameObject surface)
	{
		Chosen ch = surface.GetComponent<Chosen> ();
		if (ch != null) {
			GameObject child = NGUITools.AddChild (surface, prefab);
			child.transform.localScale = surface.transform.localScale;
				
			Transform trans = child.transform;
			float x = surface.transform.position.x;
			float y = surface.transform.position.y;
			float z = surface.transform.position.z;

			//Place cubes next to each other
			if (UICamera.lastWorldPosition.x == x + offset) {
				trans.position = new Vector3 (x + 2 * offset, y, z);
			} else if (UICamera.lastWorldPosition.y == y + offset) {
				trans.position = new Vector3 (x, y + 2 * offset, z);
			} else if (UICamera.lastWorldPosition.z == z + offset) {
				trans.position = new Vector3 (x, y, z + 2 * offset);
			} else if (UICamera.lastWorldPosition.x == x - offset) {
				trans.position = new Vector3 (x - 2 * offset, y, z);
			} else if (UICamera.lastWorldPosition.y == y - offset) {
				trans.position = new Vector3 (x, y - 2 * offset, z);
			} else if (UICamera.lastWorldPosition.z == z - offset) {
				trans.position = new Vector3 (x, y, z - 2 * offset);
			}

			child.GetComponent<Chosen> ().OnClick ();
			if (rotatePlacedObject) {
				trans.rotation = Quaternion.LookRotation (UICamera.lastHit.normal) * Quaternion.Euler (90f, 0f, 0f);
			}
			// Destroy this icon as it's no longer needed
			NGUITools.Destroy (gameObject);
			return;
		}
		base.OnDragDropRelease (surface);
	}
}
